package sysinit

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"object/go_cms/common"
	_ "object/go_cms/models"
	"time"
)

func initdb() {
	alias := beego.AppConfig.String("db_alias")
	name := beego.AppConfig.String("db_name")
	user := beego.AppConfig.String("db_user")
	pwd := beego.AppConfig.String("db_pwd")
	host := beego.AppConfig.String("db_host")
	port := beego.AppConfig.String("db_port")
	charset := beego.AppConfig.String("db_charset")

	//"root:root@tcp(127.0.0.1:3306)/go_cms?charset=utf8"
	url := user + ":" + pwd + "@tcp(" + host + ":" + port + ")/" + name + "?charset=" + charset

	err := orm.RegisterDataBase(alias, "mysql", url, 30)
	if err != nil {
		common.Logs(err.Error())
	}
	// invalid connection
	orm.SetMaxIdleConns("default", 10)
	orm.SetMaxOpenConns("default", 10)
	db, err := orm.GetDB("default")
	if err != nil {
		common.Logs(err.Error())
	}
	db.SetConnMaxLifetime(50)

	//时区
	orm.DefaultTimeLoc = time.UTC

	//如果是开发模式，显示命令信息
	isDev := beego.AppConfig.String("runmode") == "dev"

	//自动创建表
	//_ = orm.RunSyncdb(alias, false, isDev)

	if isDev {
		orm.Debug = isDev
	}
}
